package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }


    @Resource
    private MemberLevelDao memberLevelDao;

    //注册功能
    @Override
    public void regist(MemberRegistVo memberRegistVo) {

        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity memeberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memeberLevelEntity.getId());

        //检查同户名和手机号是否唯一
        checkUsername(memberRegistVo.getUsername());
        checkPhone(memberRegistVo.getPhone());


        memberEntity.setUsername(memberRegistVo.getUsername());

        // md5加密
//        String s = DigestUtils.md5Hex("12233");
//
//        //MD5 加盐
//        String s1 = Md5Crypt.md5Crypt("1234".getBytes(), "$1$krj3rj3or3");
//
        //利用spring自带的
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(memberRegistVo.getPassword());
        //解密：
        //boolean matches = bCryptPasswordEncoder.matches(memberRegistVo.getPhone(), encode);

        memberEntity.setMobile(memberRegistVo.getPhone());
        memberEntity.setPassword(encode);

        this.baseMapper.insert(memberEntity);

    }

    @Override
    public void checkUsername(String username) {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }

    }

    @Override
    public void checkPhone(String phone) {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }


    }


    //登录功能
    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {

        String loginacct = memberLoginVo.getLoginacct();
        String password = memberLoginVo.getPassword();

        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));

        if (memberEntity == null) {
            return null;
        } else {
            String password1 = memberEntity.getPassword();
            boolean matches = new BCryptPasswordEncoder().matches(password, password1);

            if (matches) {

                return memberEntity;
            } else {
                return null;
            }

        }

    }

    @Override
    public MemberEntity openId(String openId) {

        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("open_id", openId));

        if (memberEntity != null) {
            return memberEntity;
        } else {
            return null;
        }

    }

    @Override
    public MemberEntity loginWeibo(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();
        //登录和注册
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        if (memberEntity != null) {
            //已经注册过了  更新access_token和过期时间
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());

            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            //没有查到，所以要注册一个
            MemberEntity regist = new MemberEntity();
            //远程查询
            try {
                Map<String, String> map = new HashMap<>();
                map.put("access_token", socialUser.getAccess_token());
                map.put("uid", socialUser.getUid());


                //https://api.weibo.com/2/users/show.json
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);

                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);

                    //昵称
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(name);
                    regist.setUsername(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {
            }

            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());

            //插入数据库
            this.baseMapper.insert(regist);
            return regist;

        }
    }

}